package com.lvmama.pangolin.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.DateUtil;
import com.lvmama.pangolin.common.RowkeyGenerator;
import com.lvmama.pangolin.entity.ConvertTask;
import com.lvmama.pangolin.entity.Convert_Log_Model;
import com.lvmama.pangolin.entity.Festival_Model;
import com.lvmama.pangolin.entity.RuleLevelModel;
import com.lvmama.pangolin.entity.Task_History;
import com.lvmama.pangolin.service.ConvertLogService;
import com.lvmama.pangolin.service.ConvertTaskService;
import com.lvmama.pangolin.service.FestivalService;
import com.lvmama.pangolin.service.RuleLevelService;
import com.lvmama.pangolin.service.TaskHistoryService;

@Component
public class RuleUtil {
	/**  
	* @Title：CommonUtil.java
	* @Author:zhoutianqi
	* @Description:
	* @Date：2017年2月21日下午4:12:58  
	*/
	private Logger logger = Logger.getLogger(RuleUtil.class);
	@Autowired
	private FestivalService festivalService;
	@Autowired
	private TaskHistoryService taskHistoryService;
	@Autowired
	private RuleLevelService ruleLevelService;
	@Autowired
	private ConvertLogService logService;
	@Autowired
	private ConvertTaskService taskService;
	//同步锁
	private static final String TaskInfoBLOCKED = "TaskInfoBLOCKED";
	//获取节假日数据
	private List<Festival_Model> festivalList = null;
	private List<RuleLevelModel> ticketNormalLevelList = new ArrayList<RuleLevelModel>();
	//获取所有打开的super rule level
	private List<RuleLevelModel> ticketSuperLevelList = new ArrayList<RuleLevelModel>();
	private List<RuleLevelModel> hotelNormalLevelList = new ArrayList<RuleLevelModel>();
	//获取所有打开的super rule level
	private List<RuleLevelModel> hotelSuperLevelList = new ArrayList<RuleLevelModel>();
	@Value("#{'${str_max_number_1}'}")
	private String str_max_number;
	public boolean isFestivalDay(Date date){
		for(Festival_Model item:festivalList){
			if(DateUtil.isRegionDate(date, item.getStart_date(), item.getEnd_date())){
				return true;
			}
		}
		return false;
	}
	/**
	 * every time
	 * check that if taskMap contains this task info including taskID AND DATE
	 * if not ,insert current task info into task history table
	 * or contain
	*/
	public boolean addTaskInfo(String taskId,Date date,String syscode,String busType,String levelType){
		String dealTaskID = RowkeyGenerator.getNumberOfStr(taskId, Integer.parseInt(str_max_number));
		//反转后 补齐15位
		dealTaskID = RowkeyGenerator.replenish(RowkeyGenerator.reverse(dealTaskID), Integer.parseInt(str_max_number));
		String key = generateKey(dealTaskID, date, syscode);
		Task_History task = null;
		try {
			//避免异步多线程脏读
			synchronized (TaskInfoBLOCKED) {
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("id", key);
				paramMap.put("business_type", busType);
				paramMap.put("level_type", levelType);
				paramMap.put("task_id", taskId);
				paramMap.put("syscode", syscode);
				List<Task_History> task1 = taskHistoryService.getTaskByID(paramMap);
				if(task1!=null && task1.size()>0){
					return true;
				}
				task = new Task_History();
				task.setId(key);
				task.setTask_id(taskId);
				task.setCreate_Date(date);
				task.setSyscode(syscode);
				task.setBusiness_type(busType);
				task.setLevel_type(levelType);
				taskHistoryService.insertTask(task);
			}
		}catch (Exception e) {
			logger.error("CommonUtil  TaskIDINFO数据入表异常！ "+task.toString());
			logger.error("CommonUtil  TaskIDINFO数据入表异常！ "+e.getMessage());
		}
		return true;
	}
	
	public static boolean needSuperRule(Date data,List<RuleLevelModel> list){
		for(RuleLevelModel item:list){
			if(DateUtil.isRegionDate(data, item.getStart_date(), item.getEnd_date())){
				return true;
			}
		}
		return false;
	}


	/**
	 * 根据时间跨度级别获取一段时间的taskInfo
	*/
	public List<Task_History> getPartOfTask(int Rule_level,Date date,String syscode,String busType,String levelType){
		Date start_date = null;
		if(Rule_level==Constant.RULE_LEVEL_WEEK_VALUE){
			start_date=DateUtil.getDateBeforeWeek(date);
		}else if(Rule_level==Constant.RULE_LEVEL_MONTH_VALUE){
			start_date=DateUtil.getDateBeforeMonth(date);
		}else if(Rule_level==Constant.RULE_LEVEL_QUARTER_VALUE){
			start_date=DateUtil.getDateBeforeQuarter(date);
		}else if(Rule_level==Constant.RULE_LEVEL_YEAR_VALUE){
			start_date=DateUtil.getDateBeforeYear(date);
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("start_Date", start_date);
		paramMap.put("end_Date", date);
		paramMap.put("syscode", syscode);
		paramMap.put("business_type", busType);
		paramMap.put("level_type", levelType);
		List<Task_History> list = null;
		try {
			list =taskHistoryService.getTaskListByDays(paramMap);
		} catch (Exception e) {
			logger.error("RuleUtil获取taskinfo："+e.getMessage());
		}
		return list;
	}
	
	
	public double getLeftPrice(int number,double average,double left_rate){
		return average*(1-left_rate);
	}
	public double getRightPrice(int number,double average,double right_rate){
		return average*(1+right_rate);
	}
	public boolean updateTimerStatus(ConvertTask task,String status){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("status", status);
		paramMap.put("id", task.getId());
		if(status.equals(Constant.DATA_ERROR_STATE_CODE)){
			paramMap.put("run_num", task.getRunNum()+1);
		}
		try {
			taskService.updateByMap(paramMap);
		} catch (Exception e) {
			logger.error(">>>>>>>>>>>>任务："+task.getId()+"更新Timer状态失败！<<<<<<<<<<<<<");
			return false;
		}
		return true;
	}
	public boolean hasTaskIDAndCity(ConvertTask task){
		if(task.getTaskId()==null || task.getTaskId().equals("") || 
				task.getGranularityValue()==null ||
				task.getGranularityValue().equals("")){
			return false;
		}
		return true;
	}
	public void cacheFestivalData(){
		try {
			if(festivalList==null){
				festivalList = festivalService.getAllFestival(null);
			}
		} catch (Exception e) {
			logger.error("CommonUtil获取节假日数据异常！");
		}
	}
	/**
	 * 获取所有打开的normal rule level
	*/
	public void cacheNormalRuleLevels(){
		List<RuleLevelModel> normalLevelList = null;
		try {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("is_open", "1");
			paramMap.put("level_type", Constant.RULE_LEVEL_NORMAL_TYPE);
			normalLevelList = ruleLevelService.getOpenTimeLevel(paramMap);
			for(RuleLevelModel item:normalLevelList){
				if(item.getBusiness_type().equals(Constant.RULE_LEVEL_TICKET_TYPE)){
					ticketNormalLevelList.add(item);
				}else if(item.getBusiness_type().equals(Constant.RULE_LEVEL_HOTEL_TYPE)){
					hotelNormalLevelList.add(item);
				}
			}
		} catch (Exception e) {
			logger.error("CommonUtil cacheNormalRuleLevels获取过滤规则配置数据异常！");
		}
	}
	/**
	 * productID commodityID can not be null at the same time
	*/
	public boolean insertLogMesg(ConvertTask convertTask,String productID,String commodityID,Date createTime,String msg,String remark){
		Convert_Log_Model model = new Convert_Log_Model();
		model.setProduct_id(productID);
		model.setCommodity_id(commodityID);
		model.setCreate_date(createTime);
		model.setRemark(remark);
		model.setError_desc(msg);
		model.setTask_id(convertTask.getTaskId());
		model.setBusiness_type(convertTask.getBusinessType());
		model.setInsert_date(new Date());
		model.setCompany_code(convertTask.getCompanyCode());
		model.setConvert_task_id(convertTask.getId().toString());
		String id = null;
		if(productID!=null && !productID.equals("")){
			id = RowkeyGenerator.generateRowkey(productID, createTime, convertTask.getTaskId());
		}else if(commodityID!=null && !commodityID.equals("")){
			id = RowkeyGenerator.generateCommodityRowkey(commodityID, createTime, productID);
		}
		model.setId(id);
		try {
			Convert_Log_Model item = logService.queryLogByID(id);
			if(item==null){
				logService.insertLog(model);
			}
		} catch (Exception e) {
			logger.error("日志数据入表失败："+model.toString());
		}
		return true;
	}
	/**
	 * 获取所有打开的Super rule level
	*/
	public void cacheSuperRuleLevels(){
		List<RuleLevelModel> superLevelList = null;
		try {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("is_open", "1");
			paramMap.put("level_type", Constant.RULE_LEVEL_SUPER_TYPE);
			superLevelList = ruleLevelService.getOpenTimeLevel(paramMap);
			for(RuleLevelModel item:superLevelList){
				if(item.getBusiness_type().equals(Constant.RULE_LEVEL_TICKET_TYPE)){
					ticketSuperLevelList.add(item);
				}else if(item.getBusiness_type().equals(Constant.RULE_LEVEL_HOTEL_TYPE)){
					hotelSuperLevelList.add(item);
				}
			}
		} catch (Exception e) {
			logger.error("CommonUtil cacheSuperRuleLevels获取过滤规则配置数据异常！");
		}
	}
	public String generateKey(String taskId,Date date,String str){
		String yyyyMMdd = DateUtil.yyyyMMdd_NOT_.format(date);
		return taskId+yyyyMMdd+str;
	}
	public List<Festival_Model> getFestivalList() {
		return festivalList;
	}
	public void setFestivalList(List<Festival_Model> festivalList) {
		this.festivalList = festivalList;
	}
	public List<RuleLevelModel> getTicketNormalLevelList() {
		return ticketNormalLevelList;
	}
	public void setTicketNormalLevelList(List<RuleLevelModel> ticketNormalLevelList) {
		this.ticketNormalLevelList = ticketNormalLevelList;
	}
	public List<RuleLevelModel> getTicketSuperLevelList() {
		return ticketSuperLevelList;
	}
	public void setTicketSuperLevelList(List<RuleLevelModel> ticketSuperLevelList) {
		this.ticketSuperLevelList = ticketSuperLevelList;
	}
	public List<RuleLevelModel> getHotelNormalLevelList() {
		return hotelNormalLevelList;
	}
	public void setHotelNormalLevelList(List<RuleLevelModel> hotelNormalLevelList) {
		this.hotelNormalLevelList = hotelNormalLevelList;
	}
	public List<RuleLevelModel> getHotelSuperLevelList() {
		return hotelSuperLevelList;
	}
	public void setHotelSuperLevelList(List<RuleLevelModel> hotelSuperLevelList) {
		this.hotelSuperLevelList = hotelSuperLevelList;
	}
	
}
